package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.CustomerDao;
import edu.ynu.se.xiecheng.achitectureclass.dao.OrderDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.Customer;
import edu.ynu.se.xiecheng.achitectureclass.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.NoSuchElementException;
import java.util.Optional;

@Service
public class CustomerService extends LogicService<CustomerDao, Customer,Long> {
    public CustomerService(@Qualifier("customerDao") @Autowired CustomerDao dao) {
        super(dao);
    }

    @Autowired
    private OrderDao orderDao;

    public void cancelOrder(Long orderId) {
        Optional<Order> optionalOrder = orderDao.findById(orderId);
        if (optionalOrder.isPresent()) {
            Order order = optionalOrder.get();
            if (!order.isCancelled() && !order.isPaid()) {
                order.cancelOrder();
                orderDao.save(order);
            } else {
                throw new IllegalArgumentException("Unable to cancel the order");
            }
        } else {
            throw new NoSuchElementException("Order not found");
        }
    }
    public Order getOrCreateCurrentOrder(Customer customer) {
        Optional<Order> unpaidOrder = orderDao.findByCustomerAndIsPaid(customer, false);
        if (unpaidOrder.isPresent()) {
            return unpaidOrder.get();
        } else {
            Order newOrder = new Order();
            newOrder.setCustomer(customer);
            return orderDao.save(newOrder);
        }
    }
}
